﻿/******************************************************************************
文件名称    :   MySqlHospitalizationDataProvider.cs
创建日期    :   2011/5/13 6:17:15
功能描述    :   Hospitalization实体数据提供程序MySql实现类
修改日志    :   
    2011-05-13 06:17  马利
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using Dare.Utilities.Data;
using Stone.Data.Providers;
using Stone.Components.Entities;
using MySql.Data.MySqlClient;

namespace Stone.Data.MySql.Providers
{
    /// <summary>
    /// Hospitalization实体数据提供程序MySql实现类
    /// </summary>
    public class MySqlHospitalizationDataProvider : HospitalizationDataProvider
    {
        public MySqlHospitalizationDataProvider()
            : base()
        {
        }

        public override void Insert(TransactionManager manager, Hospitalization entity)
        {
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/

                //插入SQL语句
                cmd.CommandText = "insert into tb_hospitalization(date, patient_id, chemistry_id, optics_id, surgery_id, comment) values(?date, ?patient_id, ?chemistry_id, ?optics_id, ?surgery_id, ?comment);" +
                    "select id, time_stamp from tb_hospitalization where id = last_insert_id();";
                GenericDbHelper.AddParameter(mgr, cmd, "?date", DbType.Date).Value = entity.Date;
                GenericDbHelper.AddParameter(mgr, cmd, "?patient_id", DbType.Int64).Value = entity.PatientId == null ? DBNull.Value : (object)entity.PatientId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?chemistry_id", DbType.Int64).Value = entity.ChemistryId == null ? DBNull.Value : (object)entity.ChemistryId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?optics_id", DbType.Int64).Value = entity.OpticsId == null ? DBNull.Value : (object)entity.OpticsId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?surgery_id", DbType.Int64).Value = entity.SurgeryId == null ? DBNull.Value : (object)entity.SurgeryId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?comment", DbType.String).Value = entity.Comment == null ? DBNull.Value : (object)entity.Comment;

                //执行数据库操作,并获得主键和更新时间戳
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        entity.Id = reader.GetInt32(0);
                        entity.TimeStamp = reader.GetDateTime(1);
                        entity.EntityState = Stone.Components.EntityState.Saved;
                    }
                }

                //插入关联
                InsertRelations(mgr, cmd, entity);

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });
        }

        public override void Import(TransactionManager manager, IEnumerable<Hospitalization> entities)
        {
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/

                //插入SQL语句
                cmd.CommandText = "insert into tb_hospitalization(id, date, patient_id, chemistry_id, optics_id, surgery_id, comment, time_stamp) values(?id, ?date, ?patient_id, ?chemistry_id, ?optics_id, ?surgery_id, ?comment, ?time_stamp);";
                GenericDbHelper.AddParameter(mgr, cmd, "?id", DbType.Int64);
                GenericDbHelper.AddParameter(mgr, cmd, "?date", DbType.Date);
                GenericDbHelper.AddParameter(mgr, cmd, "?patient_id", DbType.Int64);
                GenericDbHelper.AddParameter(mgr, cmd, "?chemistry_id", DbType.Int64);
                GenericDbHelper.AddParameter(mgr, cmd, "?optics_id", DbType.Int64);
                GenericDbHelper.AddParameter(mgr, cmd, "?surgery_id", DbType.Int64);
                GenericDbHelper.AddParameter(mgr, cmd, "?comment", DbType.String);
                GenericDbHelper.AddParameter(mgr, cmd, "?time_stamp", DbType.DateTime);

                //执行数据库操作
                foreach (Hospitalization entity in entities)
                {
                    int i = 0;
                    cmd.Parameters[i++].Value = entity.Id;
                    cmd.Parameters[i++].Value = entity.Date;
                    cmd.Parameters[i++].Value = entity.PatientId == null ? DBNull.Value : (object)entity.PatientId.Value;
                    cmd.Parameters[i++].Value = entity.ChemistryId == null ? DBNull.Value : (object)entity.ChemistryId.Value;
                    cmd.Parameters[i++].Value = entity.OpticsId == null ? DBNull.Value : (object)entity.OpticsId.Value;
                    cmd.Parameters[i++].Value = entity.SurgeryId == null ? DBNull.Value : (object)entity.SurgeryId.Value;
                    cmd.Parameters[i++].Value = entity.Comment == null ? DBNull.Value : (object)entity.Comment;
                    cmd.Parameters[i++].Value = entity.TimeStamp;
                    cmd.ExecuteNonQuery();
                }

                //插入关联
                InsertRelations(mgr, cmd, entities);

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });
        }

        public override void Update(TransactionManager manager, Hospitalization entity)
        {
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/
                //更新SQL语句
                cmd.CommandText = "update tb_hospitalization set date = ?date, patient_id = ?patient_id, chemistry_id = ?chemistry_id, optics_id = ?optics_id, surgery_id = ?surgery_id, comment = ?comment where id = ?id;"
                        + "select time_stamp from tb_hospitalization where id = ?id;";
                GenericDbHelper.AddParameter(mgr, cmd, "?date", DbType.Date).Value = entity.Date;
                GenericDbHelper.AddParameter(mgr, cmd, "?patient_id", DbType.Int64).Value = entity.PatientId == null ? DBNull.Value : (object)entity.PatientId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?chemistry_id", DbType.Int64).Value = entity.ChemistryId == null ? DBNull.Value : (object)entity.ChemistryId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?optics_id", DbType.Int64).Value = entity.OpticsId == null ? DBNull.Value : (object)entity.OpticsId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?surgery_id", DbType.Int64).Value = entity.SurgeryId == null ? DBNull.Value : (object)entity.SurgeryId.Value;
                GenericDbHelper.AddParameter(mgr, cmd, "?comment", DbType.String).Value = entity.Comment == null ? DBNull.Value : (object)entity.Comment;
                GenericDbHelper.AddParameter(mgr, cmd, "?id", DbType.Int64).Value = entity.Id;

                //执行数据库操作,并获得更新时间戳
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        entity.TimeStamp = reader.GetDateTime(0);
                        entity.EntityState = Stone.Components.EntityState.Saved;
                    }
                }

                //更新关联
                UpdateRelations(mgr, cmd, entity);

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });
        }

        public override void Delete(TransactionManager manager, long key)
        {
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/

                //先删除关联
                DeleteRelations(mgr, cmd, key);

                //删除SQL语句
                cmd.CommandText = "delete from tb_hospitalization where id = ?id;";
                GenericDbHelper.AddParameter(mgr, cmd, "?id", DbType.Int64).Value = key;

                //执行
                cmd.ExecuteNonQuery();
                /*------------------------------数据库SQL操作结束----------------------------------*/
            });
        }

        public override void DeleteAll(TransactionManager manager, string whereClause)
        {
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------具体SQL操作开始----------------------------------*/

                //先删除关联
                DeleteRelations(mgr, cmd, whereClause);

                //删除SQL语句
                cmd.CommandText = String.Format("delete from tb_hospitalization {0}",
                     ProcessWhereClause(whereClause));

                //执行
                cmd.ExecuteNonQuery();

                /*------------------------------具体SQL操作结束----------------------------------*/
            });
        }

        public override Hospitalization Get(TransactionManager manager, long key)
        {
            Hospitalization entity = null;
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/
                //获取SQL语句
                cmd.CommandText = "select * from tb_hospitalization where id = ?id";
                GenericDbHelper.AddParameter(mgr, cmd, "?id", DbType.Int64).Value = key;

                //执行获取实体
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        entity = Fill(reader, null);
                    }
                }

                //获取关联
                if (entity != null)
                {
                    RetrieveRelations(mgr, cmd, entity);
                    entity.EntityState = Stone.Components.EntityState.Saved;
                }

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });

            return entity;
        }

        public override List<Hospitalization> GetPaged(TransactionManager manager, string whereClause, string orderBy, int pageIndex, int pageSize)
        {
            List<Hospitalization> list = new List<Hospitalization>(pageSize > 0 ? Math.Min(pageSize, 256) : 32);
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/
                //获取SQL语句
                cmd.CommandText = String.Format("select * from tb_hospitalization {0} {1} {2}",
                    ProcessWhereClause(whereClause),
                    ProcessOrderBy(orderBy),
                    ProcessPaging(pageIndex, pageSize));

                //执行获取实体集
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(Fill(reader, null));
                    }
                }

                //获取关联
                RetrieveRelations(mgr, cmd, list);

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });

            return list;
        }

        public override int GetCount(TransactionManager manager, string whereClause)
        {
            int count = 0;
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/
                //获取SQL语句
                cmd.CommandText = String.Format("select count(*) from tb_hospitalization {0}",
                    ProcessWhereClause(whereClause));

                //执行获取实体集数量
                count = Convert.ToInt32(cmd.ExecuteScalar());

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });

            return count;
        }

        public override long GetVersion(TransactionManager manager, string whereClause)
        {
            long count = 0;
            DateTime? timeStamp = null;
            Execute(manager, delegate(TransactionManager mgr, DbCommand cmd)
            {
                /*------------------------------数据库SQL操作开始----------------------------------*/
                //获取SQL语句
                cmd.CommandText = String.Format("select count(*), max(time_stamp) from tb_hospitalization {0}",
                    ProcessWhereClause(whereClause));

                //执行获取实体集数量
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        count = reader.GetInt64(0);
                        timeStamp = reader.IsDBNull(1) ? (DateTime?)null : reader.GetDateTime(1);
                    }
                }

                /*------------------------------数据库SQL操作结束----------------------------------*/
            });

            return (timeStamp ?? DateTime.MinValue).Ticks ^ count;
        }

        public override Hospitalization Fill(IDataReader reader, Hospitalization entity)
        {
            if (entity == null) entity = new Hospitalization();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                switch (reader.GetName(i))
                {
                    case "id":
                        entity.Id = reader.GetInt64(i);
                        break;
                    case "date":
                        entity.Date = reader.GetDateTime(i);
                        break;
                    case "patient_id":
                        entity.PatientId = reader[i] == DBNull.Value ? entity.PatientId : reader.GetInt64(i);
                        break;
                    case "chemistry_id":
                        entity.ChemistryId = reader[i] == DBNull.Value ? entity.ChemistryId : reader.GetInt64(i);
                        break;
                    case "optics_id":
                        entity.OpticsId = reader[i] == DBNull.Value ? entity.OpticsId : reader.GetInt64(i);
                        break;
                    case "surgery_id":
                        entity.SurgeryId = reader[i] == DBNull.Value ? entity.SurgeryId : reader.GetInt64(i);
                        break;
                    case "comment":
                        entity.Comment = reader[i] == DBNull.Value ? entity.Comment : reader.GetString(i);
                        break;
                    case "time_stamp":
                        entity.TimeStamp = reader.GetDateTime(i);
                        break;
                }
            }

            entity.EntityState = Stone.Components.EntityState.Saved;
            return entity;
        }

        #region 实体关联操作数据提供类

        #endregion


        public override List<Hospitalization> GetAllByPatient(TransactionManager manager, long patientId, string orderBy)
        {
            List<DbParameter> dbParams = new List<DbParameter>();
            StringBuilder sql = new StringBuilder();
            StringBuilder sqlCount = new StringBuilder();

            //sql.Append("select ti.mac, ti.name, ti.city, ti.location, ti.expired_date, ti.model, (select name from tb_terminal_group_info where id=ti.group_id) group_name, tc.heartbeat_interval, tc.output_type, tc.output_mode, ts.* from tb_terminal_info ti inner join tb_terminal_status ts on ts.terminal_id = ti.id left join tb_terminal_config tc on ti.id = tc.terminal_id where corp_id=?corp_id");
            //sqlCount.Append("select count(*) from tb_terminal_info ti inner join tb_terminal_status ts on ts.terminal_id = ti.id where corp_id=?corp_id");
            sql.Append("select * from tb_hospitalization where patient_id = ?patientId");

            dbParams.Add(MySqlClientUtils.CreateParameter("?patientId", MySqlDbType.Int64, patientId));

            if (!String.IsNullOrEmpty(orderBy))
            {
                sql.Append(" ").Append(ProcessOrderBy(orderBy));
            }

            return InternalGetList(manager, sql.ToString(), dbParams.ToArray());
        }

        public override List<Hospitalization> GetAllByPatientPaged(TransactionManager manager, long patientId, string orderBy, int pageIndex, int pageSize, out int totalCount)
        {
            List<DbParameter> dbParams = new List<DbParameter>();
            StringBuilder sql = new StringBuilder();
            StringBuilder sqlCount = new StringBuilder();

            sql.Append("select * from tb_hospitalization where patient_id = ?patientId");
            sqlCount.Append("select count(*) from tb_hospitalization where patient_id = ?patientId");

            dbParams.Add(MySqlClientUtils.CreateParameter("?patientId", MySqlDbType.Int64, patientId));

            if (!String.IsNullOrEmpty(orderBy))
            {
                sql.Append(" ").Append(ProcessOrderBy(orderBy));
            }

            sql.Append(" ").Append(ProcessPaging(pageIndex, pageSize));

            return InternalGetPaged<Hospitalization>(manager, sql.ToString(), sqlCount.ToString(), Fill, null, pageIndex, pageSize, out totalCount, dbParams.ToArray());
        }

    }
}
